package com.xcc.wchatrobot;

import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

public class MyAccessibilityService extends AccessibilityService {
    private static final String TAG = "TAG---->";
    private SendMsgTools sendMsgTools;

    public void onAccessibilityEvent(AccessibilityEvent event) {
        CharSequence packageName = event.getPackageName();
        if (packageName == null) {
            if (Logger.isDebug) Logger.v(TAG, "packageName:null");
            return;
        }
        int eventType = event.getEventType();
        // 输出事件的字符串type
        String typeStr = AccessibilityEvent.eventTypeToString(eventType);
        Logger.v(TAG, typeStr);
        switch (eventType) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED: {
                if (Logger.isDebug) Logger.v(TAG, "状态栏收到信息");
                if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {
                    Notification notification = (Notification) event.getParcelableData();
                    CharSequence tickerText = notification.tickerText;
                    if (tickerText != null) {
                        String s = tickerText.toString();//谢磁磁: [怄火]
                        if (Logger.isDebug) Logger.out(s);
                        //保存获取到的信息
                        String[] split = s.split(":");
                        UserMsg userMsg = MsgManage.getInstance().getUserMsg(split[0]);
                        userMsg.receiveMsg(split[1]);
                    }
                }
                //尝试开启微信
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                startActivity(intent);
            }
            break;
            default: {
                AccessibilityNodeInfo info = event.getSource();//获取根节点
                if (info == null) {
                    if (Logger.isDebug) Logger.v(TAG, "根节点为空");
                    return;
                }
                //outNodeInfo(info, 0);

                //会话详情页，可以发信息
                boolean isSC = isSpeakingContent(info);
                if (isSC) {
                    SendMsgTools sendMsgTools = getSendMsgTools();
                    sendMsgTools.start(info);
                    return;
                }
                IdControl idControl = IdControl.getInstance();
                //会话列表，检查信息或跳转
                boolean isSpeak = isSpeakingItem(info);
                if (isSpeak) {
                    //查找用户item
                    List<AccessibilityNodeInfo> itemNodeInfos = info.findAccessibilityNodeInfosByViewId(idControl.userItemId());
                    if (itemNodeInfos == null || itemNodeInfos.size() == 0) {
                        //查找菜单红点
                        itemNodeInfos = info.findAccessibilityNodeInfosByViewId(idControl.userMsgDot());
                        if (itemNodeInfos == null || itemNodeInfos.size() == 0) {
                            //performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                            return;
                        }
                        //点击菜单跳转
                        clickView(info, idControl.clickItemUser());
                    } else {
                        for (int i = 0; i < itemNodeInfos.size(); i++) {
                            AccessibilityNodeInfo itemNodeInfo = itemNodeInfos.get(i);
                            if (itemNodeInfo == null) continue;
                            //获取红点以及数量
                            List<AccessibilityNodeInfo> redDotInfos = itemNodeInfo.findAccessibilityNodeInfosByViewId(idControl.userMsgDotNumb());
                            if (redDotInfos == null || redDotInfos.size() == 0) continue;
                            AccessibilityNodeInfo nodeInfo = redDotInfos.get(0);
                            CharSequence numb = nodeInfo.getText();//红点数量
                            if (numb == null) continue;
                            //获取昵称
                            redDotInfos = itemNodeInfo.findAccessibilityNodeInfosByViewId(idControl.userName());
                            if (redDotInfos == null || redDotInfos.size() == 0) continue;
                            nodeInfo = redDotInfos.get(0);
                            CharSequence userName = nodeInfo.getText();
                            if (userName == null) continue;
                            if (Logger.isDebug)
                                Logger.v(TAG, "用户:" + userName.toString() + " 未读信息数:" + numb.toString());
                            //点击跳转
                            clickView(itemNodeInfo, idControl.userItemId());
                        }
                    }
                }
            }
            break;
        }
    }

    public void onInterrupt() {
    }

    //遍历所有节点
    private void outNodeInfo(AccessibilityNodeInfo info, int idx) {
        int childCount = info.getChildCount();
        for (int i = 0; i < childCount; i++) {
            AccessibilityNodeInfo child = info.getChild(i);
            if (child != null) {
                String builder = "-----------" + idx + "-----------" +
                        "\n节点id:" + child.getViewIdResourceName() +
                        "\nclassName:" + child.getClassName() +
                        "\ntext:" + child.getText();
                Logger.v(TAG, builder);
                outNodeInfo(child, idx + 1);
            }
        }
        if (childCount == 0) {
            Rect outBounds = new Rect();
            info.getBoundsInScreen(outBounds);
            Logger.v(TAG, "-----------" + idx + "-----------" + "空位置：" + outBounds);
        }
    }

    //是会话列表
    private boolean isSpeakingItem(AccessibilityNodeInfo info) {
        if (BuildConfig.DEBUG) {
            int childCount = info.getChildCount();
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = info.getChild(i);
                CharSequence className = child.getClassName();
                String idResourceName = child.getViewIdResourceName();
                Logger.out("className:" + className + " idResourceName:" + idResourceName);
            }
        }
        List<AccessibilityNodeInfo> viewInfos = info.findAccessibilityNodeInfosByViewId(IdControl.getInstance().userList());
        if (viewInfos == null || viewInfos.size() == 0) return false;
        AccessibilityNodeInfo nodeInfo = viewInfos.get(0);
        CharSequence className = nodeInfo.getClassName();
        if (className != null && "com.tencent.mm.ui.mogic.WxViewPager".equals(className.toString())) {
            return true;
        } else if (className != null && "android.widget.ListView".equals(className.toString())) {
            return true;
        } else if (className != null && "android.widget.LinearLayout".equals(className.toString())) {
            return true;
        }
        return false;
    }

    //是会话详情
    private boolean isSpeakingContent(AccessibilityNodeInfo info) {
        List<AccessibilityNodeInfo> viewInfos = info.findAccessibilityNodeInfosByViewId(IdControl.getInstance().userChatEditContent());
        if (viewInfos == null || viewInfos.size() == 0) return false;
        AccessibilityNodeInfo nodeInfo = viewInfos.get(0);
        CharSequence className = nodeInfo.getClassName();
        if (className != null && "android.widget.EditText".equals(className.toString())) {
            return true;
        }
        return false;
    }

    private SendMsgTools getSendMsgTools() {
        if (sendMsgTools == null) sendMsgTools = new SendMsgTools();
        return sendMsgTools.setService(this);
    }

    // 设置输入框信息
    public void setEditText(AccessibilityNodeInfo info, String viewId, String text) {
        List<AccessibilityNodeInfo> viewInfos = info.findAccessibilityNodeInfosByViewId(viewId);
        if (viewInfos == null || viewInfos.size() == 0) return;
        AccessibilityNodeInfo nodeInfo = viewInfos.get(0);
        if (nodeInfo == null) return;
        CharSequence className = nodeInfo.getClassName();
        if (className != null && "android.widget.EditText".equals(className.toString())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Bundle arguments = new Bundle();
                arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
            } else {
                ClipData data = ClipData.newPlainText("reply", text);
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                if (clipboardManager == null) return;
                clipboardManager.setPrimaryClip(data);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS); // 获取焦点
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE); // 执行粘贴
            }
        }
    }

    //点击按钮
    public void clickView(AccessibilityNodeInfo info, String viewId) {
        List<AccessibilityNodeInfo> viewInfos = info.findAccessibilityNodeInfosByViewId(viewId);
        if (viewInfos == null || viewInfos.size() == 0) return;
        AccessibilityNodeInfo nodeInfo = viewInfos.get(0);
        if (nodeInfo == null) return;
        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
    }

    //获取text文本
    public String getText(AccessibilityNodeInfo info, String viewId) {
        List<AccessibilityNodeInfo> nodeInfos = info.findAccessibilityNodeInfosByViewId(viewId);
        if (nodeInfos == null || nodeInfos.size() == 0) return null;
        AccessibilityNodeInfo nodeInfo = nodeInfos.get(0);
        CharSequence userName = nodeInfo.getText();
        if (userName == null) return null;
        return userName.toString();
    }
}
